package com.example.demo.utils;


import com.lowagie.text.*;
import com.lowagie.text.rtf.RtfWriter2;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

//import org.jsoup.Jsoup;
//import org.jsoup.nodes.Document;
//import org.jsoup.nodes.Element;
//import org.jsoup.select.Elements;

public class Html2WordUtils {
    public String getContent(InputStream ises) throws IOException {
        if (ises != null) {
            StringBuilder result = new StringBuilder();
            BufferedReader br;
            String line;

            br = new BufferedReader(new InputStreamReader(ises, "UTF-8"));
            while ((line = br.readLine()) != null) {
                result.append(line);
            }

            return result.toString();
        }
        return null;
    }

    public String readFile(File file) throws IOException {
        InputStream in = new FileInputStream(file);
        byte[] tempbytes = new byte[1024];
        int byteread = 0;
        //sb中存储文件内容
        StringBuilder sb = new StringBuilder();
        while ((byteread = in.read(tempbytes)) != -1) {
            //  System.out.write(tempbytes, 0, byteread);
            String str = new String(tempbytes, 0, byteread);
            sb.append(str);
        }
        return sb.toString();
    }

    //只适合文字
    public String html2word(HttpServletRequest request, HttpServletResponse response, String html) throws IOException {

        byte[] b = html.getBytes("GBK");  //这里是必须要设置编码的，不然导出中文就会乱码。
        ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
        //生成word
        POIFSFileSystem poifs = new POIFSFileSystem();
        DirectoryEntry directory = poifs.getRoot();
        DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
        String targetFileName = this.getClass().getResource("/").getPath() + "static/word/tmp.doc";
        FileOutputStream ostream = new FileOutputStream(targetFileName);
        poifs.writeFilesystem(ostream);
        bais.close();
        ostream.close();
        return targetFileName;

//        POIFSFileSystem poifs = new POIFSFileSystem();
//        DirectoryEntry directory = poifs.getRoot();
//        DocumentEntry documentEntry = directory.createDocument("文档名称", bais);
//        //输出文件
//        request.setCharacterEncoding("utf-8");
//        response.setContentType("application/msword");//导出word格式
//        response.addHeader("Content-Disposition", "p_w_upload;filename=" + new String( (documentEntry.getName() + ".doc").getBytes(), StandardCharsets.ISO_8859_1));
//        OutputStream ostream = response.getOutputStream();
//        poifs.writeFilesystem(ostream);
//        bais.close();
//        ostream.close();
//        return response;


    }

    //解析html
    private List<Object> html2jsoup(String html) throws IOException, BadElementException {
        org.jsoup.nodes.Document document = Jsoup.parse(html);
        Elements links = document.select("body > *");

        List<Object> list = new ArrayList<Object>();
        if(!document.wholeText().equals("") && links.size()==0){
            list.add(document.wholeText());
            list.add("\n");
        }
        for (Element o : links) {
//            Elements i = o.select("*");
//            //如果是多层，则递归
//            if(i.size()>1) {
//                list.addAll(html2jsoup(o.wholeText()));
//
//            }
            if(o.childNodeSize()>=1){
                for (Node child:o.childNodes()) {
                    list.addAll(html2jsoup((child.toString())));
                }
            }else {
                //如果是单层，则判断是否是图片
                String src = o.attr("src");
                String tmp = "";
                if (src.equals("")) {
                    tmp = o.wholeText();
                    list.add(tmp);
                    list.add("\n");
                } else {
                    tmp = src.substring(src.indexOf(",") + 1);
                    BASE64Decoder decoder = new BASE64Decoder();
                    byte[] imageByte = decoder.decodeBuffer(tmp);//图片-- 字节流方式写入
                    Image img = Image.getInstance(imageByte);
                    img.setAbsolutePosition(0, 0);
                    img.setAlignment(Image.LEFT);// 设置图片显示位置
                    list.add(img);
                    list.add("\n");
                }
            }

        }
        return list;
    }

    public String ItextCreatRTF(String html) throws IOException, DocumentException {
        //将转出的doc文件放到本地临时文件里面
        String targetFileName = this.getClass().getResource("/").getPath() + "static/word/tmp.doc";
        OutputStream out = new FileOutputStream(targetFileName);
        //创建doc实例
        Document document = new Document(PageSize.A4);
        RtfWriter2.getInstance(document, out);
        document.open();
        Paragraph context = new Paragraph();
        //解析html元素
        List<Object> elements = html2jsoup(html);
        context.addAll(elements);
        document.add(context);
        document.close();
        return targetFileName;
    }


}
